<template>
  <el-dialog :visible.sync="visible" custom-class="dialog_big" @close="resetForm"	width="1200">
    <div slot="title" class="flex_row-jcsb">
      <slot name="title">
        <span class="el-dialog__title">{{$t('label_warehouse_config')}}</span>
      </slot>
      <!-- <span class="newDate">当前日期：{{ currentDate }}</span> -->
    </div>
    <el-form :model="formData" :rules="rules" ref="ruleForm" label-width="120px">
      <el-row :gutter="20" v-if="isEdit">
        <el-col :span="12">
          <el-form-item :label="$t('label_warehouse_capacity')" prop="warehouseCapacity">
            <el-row>
              <el-col :span="12">
                <el-select v-model="formData.configTypeEnum" :disabled="!userEdit" :placeholder="$t('tip_please_select')" style="margin-right: 24px;">
                  <el-option v-for="(item,index) in $enumOptions.ScheduleConfigTypeEnum" :key="index" :label="$t('ScheduleConfigTypeEnum__'+item)" :value="item"></el-option>

                </el-select>
              </el-col>
              <el-col :span="12">
                <el-input v-model.number="formData.warehouseCapacity" @input="inputnum" :disabled="!userEdit" type="number" :placeholder="$t('tip_please_warehouse_storage')">
                  <template slot="append">{{ $t('label_warehouse_cube') }}</template>
                </el-input>
              </el-col>
            </el-row>


          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item v-if="formData.configTypeEnum==='STORAGE_RANGE'" :label="$t('label_warehouse_capacity_factor')" required>
              <el-form-item  prop="capacityRateMin" style="display: inline-block;margin-bottom: 0;">
                <el-input-number :disabled="!userEdit" v-model.number="formData.capacityRateMin" :min="1" :max="100" :label="$t('tip_please_warehouse_minimum_critical_value')"></el-input-number>
              </el-form-item>
              <span class="line" :span="2" style="text-align: center;">-</span>
              <el-form-item prop="capacityRateMax"  style="display: inline-block;margin-bottom: 0;">
                <el-input-number :disabled="!userEdit" v-model.number="formData.capacityRateMax" :min="1" :max="100" :label="$t('tip_please_warehouse_maximum_critical_value')"></el-input-number>
              </el-form-item>
            <!-- <el-slider
            v-model="formData.slider"
            range
            :marks="marks">
          </el-slider> -->
          </el-form-item>
         <div v-else>&nbsp;</div>
        </el-col>
        <el-col :span="3" style="text-align: right;">
          <el-button @click="userEdit=!userEdit" type="primary">{{ $t('label_warehouse_adjustment_button') }}</el-button>
        </el-col>
      </el-row>
      <el-row :gutter="20" v-if="isEdit">
        <el-col :span="12">
          <el-form-item :label="$t('label_warehouse_appointment_time_requirements')" prop="schedulePeriodTypeEnum">
            <el-select v-model="formData.schedulePeriodTypeEnum" :placeholder="$t('tip_please_select')">
              <el-option v-for="(item,index) in $enumOptions.SchedulePeriodTypeEnum" :key="index" :label="$t('SchedulePeriodTypeEnum__'+item)" :value="item"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('label_warehouse_scheduling_system')" prop="warehouseScheduleTypeEnum">
            <el-select v-model="formData.warehouseScheduleTypeEnum" :placeholder="$t('tip_please_select')">
              <el-option v-for="(item,index) in $enumOptions.WarehouseScheduleTypeEnum" :key="index" :label="$t('WarehouseScheduleTypeEnum__'+item)" :value="item"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item v-if="isEdit" :label="$t('label_warehouse_personnel_handling_cargo_volume_situation')" prop="configDetailList" label-width="165px">
        <el-button type="warning" style="float: right;" @click="clearSchedule">{{ $t('label_clear_cargo_volume_settings') }}</el-button>
      </el-form-item>
      <el-calendar  v-model="currentDate" :class="{calendarEdit:!isEdit}">
        <template
          slot="dateCell"
          slot-scope="{date, data}">
          <p :class="data.isSelected ? 'is-selected' : ''" style="margin: 4px 0;">
            {{ data.day.split('-').slice(1).join('-') }}
            {{ data.isSelected ? '✔️' : ''}}
          </p>

          <el-input
            v-model.number="formData.schedule[(new Date(date)).getTime()]"
            type="number"
            v-if="isEdit && (dateFormatDay(data.day) >= dateFormatDay($dateFormat((new Date()).getTime()).split(' ')[0])) && data.type==='current-month' && isEdit">
            <template slot="append">{{$t('label_boxorpiece')}}</template>
          </el-input>
          <p v-else-if="formData.schedule[(new Date(date)).getTime()]">{{formData.schedule[(new Date(date)).getTime()] }}箱/件</p>
        </template>
      </el-calendar>
    </el-form>

    <div slot="footer" class="dialog_button_footer">
        <el-button type="primary" @click="submitForm">{{ $tt('label_confirm') }}</el-button>
        <el-button @click="resetForm">{{ $tt('label_cancel') }}</el-button>
      </div>
</el-dialog>
</template>

<script>

export default {
  name: 'settings',
  data() {
    return {
      visible: false,
      loading: false,
      // 点击调整按钮可以主动编辑，如果是首次 userEdit为true
      userEdit:false,
      currentDate:'',
      schedulePeriodTypeEnum:[],
      warehouseScheduleTypeEnum:[],
      isWarehouseCapacity:false,
      formData:{
        "warehouseCapacity":'',
        "capacityRateMin":70,
        "capacityRateMax":80,
        "schedulePeriodTypeEnum":"",
        "warehouseScheduleTypeEnum":"",
        "year":'',
        "month":'',
        configDetailList:[],
        schedule:{},
        configTypeEnum:'STARAGE_ONE_DAY'
      },
      rules:{
        warehouseCapacity:[{ required: true, message: this.$t('tip_please_warehouse_storage'), trigger: 'blur' }],
        capacityRateMin:[{ required: true, message: this.$t('tip_please_warehouse_minimum_critical_value'), trigger: 'blur' }],
        capacityRateMax:[{ required: true, message: this.$t('tip_please_warehouse_maximum_critical_value'), trigger: 'blur' }],
        schedulePeriodTypeEnum:[{ required: true, message: this.$t('label_warehouse_appointment_time_requirements'), trigger: 'blur' }],
        warehouseScheduleTypeEnum:[{ required: true, message: this.$t('label_warehouse_scheduling_system'), trigger: 'blur' }],
        configDetailList:[{ required: true,type:'array', message: this.$t('tip_please_fill_least_one_day'), trigger: 'blur' }],
      },
      marks: {
          0: '0%',
          20: '20%',
          40: '40%',
          60: '60%',
          80: {
            style: {
              color: '#E6A23C'
            },
            label: '80%'
          },
          90: {
            style: {
              color: '#F56C6C'
            },
            label: '90%'
          },
      },
      isEdit:true,
      calendar:new Date()
    }
  },
  watch:{
    currentDate:{//监听月份变化
      handler(newValue,oldValue){
        if(typeof newValue === "string"){
          newValue = new Date(newValue)
        }
        if(typeof oldValue === "string"){
          oldValue = new Date(oldValue)
        }
        const newMonth =  newValue.getMonth() + 1
        const oldMonth =  oldValue.getMonth() + 1
        if(newMonth!==oldMonth){
          if(this.isEdit){
            this.queryMonth(newValue)
          }

        }
      }
    }
  },
  mounted() {
    this.currentDate = this.$dateFormat((new Date().getTime()))
  },
  methods: {
    // 限制只能在输入框中输入小数点后两位
    inputnum(){
        	this.formData.warehouseCapacity = this.formData.warehouseCapacity.toString().replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');
    },
    show(data = {row:{},edit:false}) {
      this.currentDate = this.$dateFormat((new Date().getTime()))
      this.isEdit = data.edit
      this.visible = true
      if(this.isEdit){
        this.query()
      }else{
        this.queryHistory(data.row.id)
        this.currentDate = `${data.row.year}-${data.row.month}-01 00:00`
        // console.log(this.currentDate,`${data.row.year}-${data.row.month} 00:00`)
      }
    },
    hide() {
      this.visible = false
      this.userEdit=false
    },
    dateFormatDay(data){
     return (new Date(data)).getTime()
    },
    clearSchedule(){
     const currentDate = new Date()
     const time = (new Date(`${currentDate.getFullYear()}-${currentDate.getMonth()+1}-${currentDate.getDate()}`)).getTime()
      console.log(time)
      // this.formData.schedule = {}
      Object.keys(this.formData.schedule).forEach(key=>{
        if(key>=time){
          this.formData.schedule[key]=''
        }
      })
    },
    queryHistory(configLogId){
      this.$ajax({
        url: "/wms-api/inbound/WmsInboundScheduleConfigRpc/selectConfigDetailLogByConfigLogId.json",
        method: 'post',
        // type:'json',
        data:{
          configLogId
        },
        success: (res) => {

          if(res.data.rows){
           this.formData.schedule = this.transformObj(res.data.rows)
          }

        }
      })
    },
    query(){
      this.$ajax({
        url: "/wms-api/inbound/WmsInboundScheduleConfigRpc/toEdit.json",
        method: 'get',
        tip: true,
        success: ({data}) => {
          if(!data) {
            // 没数据为首次设置 可以编辑
            this.userEdit = true
            return
          }
          this.isWarehouseCapacity=!!data.warehouseCapacity
          Object.assign(this.formData,{
            id:data.id,
            warehouseCapacity:data.warehouseCapacity,
            configTypeEnum:data.configTypeEnum,
            capacityRateMin:data.capacityRateMin,
            capacityRateMax:data.capacityRateMax,
            schedulePeriodTypeEnum:data.schedulePeriodTypeEnum,
            warehouseScheduleTypeEnum:data.warehouseScheduleTypeEnum,
            year:data.warehouseScheduleTypeEnum,
            month:data.month,
            configDetailList:[],
            schedule:{},
          })
          if(data.configDetailList){
           this.formData.schedule = this.transformObj(data.configDetailList)
          }

        }
      })
    },
    // 按月份查找
    queryMonth(date){
      if(typeof date === "string"){
        date = new Date(date)
      }
      this.$ajax({
        url: "/wms-api/inbound/WmsInboundScheduleConfigRpc/getConfigDetailList.json",
        method: 'post',
        type:'json',
        data:{
          year:date.getFullYear(),
          month:date.getMonth()+1
        },
        success: (res) => {

          if(res.data.rows){
           this.formData.schedule = this.transformObj(res.data.rows)
          }

        }
      })
    },
    submitForm() {
      if(!this.isEdit){
        this.resetForm()
        return
      }

      if(typeof this.currentDate === "string"){
        this.currentDate = new Date(this.currentDate)
      }
      this.formData.year = this.currentDate.getFullYear()
      this.formData.month = this.currentDate.getMonth()+1
      this.formData.configDetailList = this.transformArr(this.formData.schedule)

      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {

          if(this.formData.capacityRateMax<=this.formData.capacityRateMin){
            this.$message.success(this.$t('tip_warehouse_min_max_critical_value'))
            return
          }

          this.$ajax({
            url: "/wms-api/inbound/WmsInboundScheduleConfigRpc/edit.json",
            method: 'post',
            data:this.formData,
            type: "json",
            loading: true,
            success: (res) => {

            this.$emitPage('warehouse_appointment>confirm', 'reload')
            this.$emitPage('appointment>settings_list', 'reload')
              this.resetForm()
              this.$message.success(this.$tt("tip_submit_success"))
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    transformArr(data){
      const arr = []
      Object.keys(data).forEach(key=>{
        const date = new Date(Number(key));
        // 输入了数量的才需要加入到数组
        // 只记录当前选中的月份
        if(data[key]){
          if(date.getFullYear()===this.formData.year && this.formData.month ===date.getMonth() + 1){
            arr.push({
              configDatetime:key,
              day:date.getDate(),
              month:date.getMonth() + 1,
              num:data[key],
              configDate:(new Date(`${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} 00:00:00`)).getTime()
            })
          }

        }

      })
      return arr
    },
    transformObj(data=[]){
      const obj = {}
      data.forEach(item=>{
        obj[item.configDatetime] = item.num
      })
      return obj
    },
    resetForm() {
      this.$refs['ruleForm'].resetFields();
      this.$data.formData = {
        "warehouseCapacity":'',
        "capacityRateMin":70,
        "capacityRateMax":80,
        "schedulePeriodTypeEnum":"",
        "warehouseScheduleTypeEnum":"",
        "year":'',
        "month":'',
        configDetailList:[],
        schedule:{},
        configTypeEnum:'STARAGE_ONE_DAY'
      }
      this.visible=false;
      this.userEdit=false
    },
  }
}
</script>

<style lang="less" scoped>
.newDate{
  float: right;
  margin-right: 40px;
}
.el-select{
  display: block;
}

/deep/.calendarEdit .el-calendar__button-group {
    display: none;
  }

/deep/.calendarEdit{
  .next,.prev,.current{
    pointer-events: none;
  }
}
</style>
